using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using TangMonk.Models;

namespace TangMonk.Service;

public class UserBaseService
{
    private readonly IMongoCollection<User> _userCollection;

    public UserBaseService(IOptions<MongoDatabaseSetting> mongoSetting)
    {
        var client = new MongoClient(mongoSetting.Value.ConnectionString);
        var database = client.GetDatabase(mongoSetting.Value.DatabaseName);
        _userCollection = database.GetCollection<User>(mongoSetting.Value.UserCollection);
    }

    public async Task<User> GetOne(string id)
    {
        return await _userCollection.FindAsync(x => x.Id == id).Result.FirstOrDefaultAsync();
    }

    public async Task<List<User>> GetAll()
    {
        return await _userCollection.FindAsync(x => true).Result.ToListAsync();
    }

    public async Task CreateOne(User user)
    {
        try
        {
            await _userCollection.InsertOneAsync(user);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    public async Task UpdateOne(User user)
    {
        var filter = Builders<User>.Filter.Eq(x => x.Id, user.Id);
        await _userCollection.ReplaceOneAsync(filter, user);
    }

    public RequestUserResult Login(UserLoginType type, string credential, string password)
    {
        var loginContext = new LoginContext(_userCollection);
        var result = loginContext.Login(type, credential, password);
        return result;
    }
}